<template>
  <el-dialog
      :visible.sync="dialogVisible"
      title="钉钉导入"
      width="50%"
  >
    <el-cascader
        :options="detpList"
        size="mini"
        style="width: 100%"
        @change="handleChange"
    ></el-cascader>
    <el-table
        :data="tableData"
        size="mini"
        style="width: 100%"
    >
      <el-table-column
          label="头像"
          width="80"
      >
        <template slot-scope="scope">
          <el-avatar
              :src="scope.row.avatar"
              shape="square"
              size="small"
          >头像
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column
          label="用户名"
          prop="username"
          width="150"
      >
      </el-table-column>
      <el-table-column
          label="姓名"
          prop="nickname"
          width="100"
      ></el-table-column>
      <el-table-column
          label="手机号码"
          prop="mobile"
          width="100"
      >
      </el-table-column>
      <el-table-column
          label="电子邮箱"
          prop="email"
      >
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          width="80"
      >
        <template slot-scope="scope">
          <el-button
              :disabled="scope.row.id!=null"
              size="small"
              type="text"
              @click="importUser(scope.row)"
          >导入
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>
<script>
import {dingTalkDeptListApi, dingTalkDeptUserListApi, saveUserApi,} from "@/api/user";

export default {
  data() {
    return {
      deptId: null,
      tableData: [],
      selectedDept: [],
      detpList: [],
      dialogVisible: false,
    };
  },
  methods: {
    open() {
      this.dialogVisible = true;
      this.loadDept();
    },
    async loadDept() {
      this.detpList = [];
      let list = await dingTalkDeptListApi();
      this.detpList = this.getDetpChildren(1, list);
    },
    getDetpChildren(pid, list) {
      let children = list
          .filter((d) => d.parentId == pid)
          .map((d) => {
            return {value: d.deptId, label: d.name};
          });
      if (children) {
        children.forEach((d) => {
          let c = this.getDetpChildren(d.value, list);
          if (c.length > 0) {
            d.children = c;
          }
        });
      }
      return children;
    },
    handleChange(value) {
      this.deptId = value[value.length - 1];

      this.loadUserList();
    },
    async loadUserList() {
      this.tableData = await dingTalkDeptUserListApi(this.deptId);
    },
    async importUser(user) {
      await saveUserApi(user);
      this.loadUserList();
      this.$parent.$refs.pagination.go(1);
    },
  },
};
</script>